package com.sandau.b230111.b23011123.controller;

import com.sandau.b230111.b23011123.model.Employee;
import com.sandau.b230111.b23011123.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;

@Controller
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @RequestMapping("list")
    public String list(ModelMap map, Employee employee){
        if ("".equals(employee.getName()))
        {
            employee.setName(null);
        }
        if ("".equalsIgnoreCase(employee.getDepartment())){
            employee.setDepartment(null);
        }
        map.put("employeelist",employeeService.finAll(employee));
        return "employee/list";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        employeeService.deleteById(id);
        return "redirect:/employee/list";
    }

    @RequestMapping("create")
    public String create(){
        return"employee/create";
    }

    @RequestMapping("save")
    public String save(Employee s) {
        if(s.getId() == null){
            s.setId(UUID.randomUUID().toString());
            employeeService.save(s);
        }
        else{
            employeeService.update(s);
        }
        return "redirect:/employee/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map) {
        Employee s =employeeService.getReferenceById(id);
        map.put("employee",s);
        return "employee/update";
    }
}
